<template>
  <div class="self_adaption">
    <div class="main df">
      <div class="left">
        <img class="logo" src="../assets/images/LIECHEBAO.png" alt="" />
      </div>
      <div class="right df aic jcc">
        <div class="right_content">
          <div class="right_content_top df aie jcsb">
            <h1>登录</h1>
            <p>没有账号？<a href="http://code.cyrsum.com/">去注册</a></p>
          </div>
          <div class="right_content_from">
            <el-tabs v-model="activeName" class="demo-tabs" tab-bar-style="border:none;">
              <el-tab-pane label="密码登录" name="first">
                <el-form :rules="rules" :model="account" ref="ruleFormRef">
                  <!-- 用户名 -->
                  <el-form-item prop="username">
                    <el-input @blur="checkAccount" v-model="account.username" placeholder="输入用户名">
                      <template #prefix>
                        <el-icon size="large">
                          <User />
                        </el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                  <!-- 密码 -->
                  <el-form-item prop="password">
                    <el-input v-model="account.password" placeholder="输入密码" show-password>
                      <template #prefix>
                        <el-icon size="large">
                          <Lock />
                        </el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                  <!-- 验证码 -->
                  <el-form-item prop="ValidateCode">
                    <div style="width: 100%" class="df aic jcsb">
                      <el-input
                        v-model="account.ValidateCode"
                        placeholder="请输入验证码"
                        style="width: calc(100% - 112px)">
                        <template #prefix>
                          <el-icon size="large">
                            <Reading />
                          </el-icon>
                        </template>
                      </el-input>
                      <img style="height: 3rem; border-radius: 0.25rem" @click="refreshCode" :src="baseImg" />
                    </div>
                  </el-form-item>

                  <!-- 协议  -->
                  <el-form-item prop="agreement">
                    <el-checkbox-group v-model="account.agreement">
                      <el-checkbox label="我已阅读并同意" name="agreement"> 我已阅读并同意 </el-checkbox>
                    </el-checkbox-group>
                    <a class="blue" @click="privacy">《劣车宝商城平台隐私政策》</a>和
                    <a class="blue" @click="serve">《劣车宝商城平台用户服务协议》</a>
                  </el-form-item>
                  <!-- 登录 -->
                  <el-form-item>
                    <el-button type="primary" @click="bindLogin(ruleFormRef)" :loading="flag">登录</el-button>
                  </el-form-item>
                  <!-- 记住密码  -->
                  <el-form-item prop="remmberPsw">
                    <div style="width: 100%" class="df jcsb aic">
                      <el-checkbox v-model="account.remmberPsw" label="记住密码"></el-checkbox>
                      <a style="color: #116cf8" href="#" @click="centerDialogVisible = true">忘记密码</a>
                    </div>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>

      <!-------------------------------------- 忘记密码 -------------------------------------->
      <el-dialog v-model="centerDialogVisible" :show-close="false" width="500" align-center>
        <div style="width: 100%; padding: 3.75rem 1.25rem 5rem 1.25rem; position: relative">
          <el-icon style="position: absolute; top: -1rem; right: 0" size="18" @click="backLogin">
            <CloseBold />
          </el-icon>
          <!-- 步骤条 -->
          <el-steps :active="steps" align-center size="small">
            <el-step title="验证手机号" />
            <el-step title="重置登录密码" />
            <el-step title="重置成功" />
          </el-steps>
          <!-- /*/*/*/*/*/*/*/*  验证手机号  /*/*/*/*/*/*/*/* -->
          <div class="df fdc aic jcc" style="margin-top: 2.5rem" v-if="steps == 1">
            <el-form :rules="phoneRules" :model="phoneCheck" ref="phoneRef" style="width: 50%" size="small">
              <el-form-item prop="phone">
                <el-input v-model="phoneCheck.phone" placeholder="输入手机号">
                  <template #prefix>
                    <el-icon size="large">
                      <Iphone />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="code">
                <el-input v-model="phoneCheck.code" placeholder="输入验证码">
                  <template #prefix>
                    <el-icon size="large">
                      <DataAnalysis />
                    </el-icon>
                  </template>

                  <template #suffix>
                    <span
                      style="color: #116cf8; cursor: pointer; user-select: none"
                      @click="getValidatedCode"
                      v-if="getCodeFlag == false"
                      >获取验证码</span
                    >
                    <span style="color: #116cf8; cursor: pointer; user-select: none" v-else
                      >{{ seconds }}s后重新获取</span
                    >
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <div style="width: 100%; display: flex; align-items: center; justify-content: center">
                  <el-button type="primary" @click="forgetNext(phoneRef)">下一步</el-button>
                </div>
              </el-form-item>
            </el-form>
            <div @click="backLogin" style="font-size: 0.75rem; color: #b2b2b2; cursor: pointer; user-select: none">
              无需找回？<span style="color: #116cf8">立即登录</span>
            </div>
          </div>
          <!-- /*/*/*/*/*/*/*/*  重置登录密码  /*/*/*/*/*/*/*/* -->
          <div class="df fdc aic jcc" style="margin-top: 2.5rem" v-if="steps == 2">
            <el-form :rules="passRules" :model="setPassWord" ref="passRef" style="width: 50%" size="small">
              <el-form-item prop="oldPassWord">
                <el-input v-model="setPassWord.oldPassWord" placeholder="请输入新密码">
                  <template #prefix>
                    <el-icon size="large">
                      <Lock />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="recPassWord">
                <el-input v-model="setPassWord.recPassWord" placeholder="请再次确认新密码">
                  <template #prefix>
                    <el-icon size="large">
                      <Lock />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="savePassBtn(passRef)">下一步</el-button>
              </el-form-item>
            </el-form>
            <div @click="backLogin" style="font-size: 0.75rem; color: #b2b2b2; cursor: pointer; user-select: none">
              无需找回？<span style="color: #116cf8">立即登录</span>
            </div>
          </div>
          <!-- /*/*/*/*/*/*/*/*  重置成功  /*/*/*/*/*/*/*/* -->
          <div class="df fdc aic jcc" style="margin-top: 2.5rem" v-if="steps == 3">
            <img src="../assets/images/check-circle.png" alt="" />
            <span class="passTips">新密码设置成功，请重新登录</span>
            <el-form
              style="width: 50%; display: flex; align-items: center; justify-content: center; margin-top: 8px"
              size="small">
              <el-form-item>
                <el-button type="primary" @click="backLogin">返回登录</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref} from 'vue';
import {MD5} from 'crypto-js';
import {User, Lock, Reading, Iphone, DataAnalysis} from '@element-plus/icons-vue';
import {
  RequestLOGIN,
  RequestEmployeeGetfunctionTree,
  RequestGetValidateCodeImage,
  RequestSysFunctionGettree,
  RequestAgreementGetAgreementUseLocation,
  RequestLoginAccountGetValidatedCode,
  RequestLoginAccountValidateOldMobile,
  RequestLoginAccountForgetPassword,
} from '../api/path/index.js';
import {ElMessage} from 'element-plus';
import type {FormInstance} from 'element-plus';
import {useRouter} from 'vue-router';
const router = useRouter();
const ruleFormRef = ref<FormInstance>();

/**************************** 忘记密码 ****************************/
const centerDialogVisible = ref<any>(false);
const steps = ref<any>(1);
const seconds = ref<any>(60);
const getCodeFlag = ref<any>(false);
const phoneCheck = ref<any>({
  phone: '',
  code: '',
});
const setPassWord = ref<any>({
  oldPassWord: '',
  recPassWord: '',
});
const phoneRules = ref({
  phone: [
    {required: true, message: '请输入电话', trigger: 'blur'},
    {
      pattern: /^1[3456789]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
  code: [{required: true, message: '请输入验证码', trigger: 'blur'}],
});
const phoneRef = ref(null);
const passRules = ref({
  oldPassWord: [
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {
      pattern: /^\S*$/,
      message: '密码不能有空格',
      trigger: 'blur',
    },
    {
      pattern: /^[^\u4e00-\u9fa5]*$/,
      message: '密码不能有汉字',
      trigger: 'blur',
    },
    {
      pattern: /^.{6,20}$/,
      message: '请输入6~20位的密码',
      trigger: 'blur',
    },
  ],
  recPassWord: [
    {required: true, message: '请确认新密码', trigger: 'blur'},
    {
      pattern: /^\S*$/,
      message: '密码不能有空格',
      trigger: 'blur',
    },
    {
      pattern: /^[^\u4e00-\u9fa5]*$/,
      message: '密码不能有汉字',
      trigger: 'blur',
    },
    {
      pattern: /^.{6,18}$/,
      message: '请输入6~20位的密码',
      trigger: 'blur',
    },
  ],
});
const passRef = ref(null);
// 获取验证码
const getValidatedCode = () => {
  RequestLoginAccountGetValidatedCode(phoneCheck.value.phone).then((res: any) => {
    if (res.success == true) {
      getCodeFlag.value = true;
      ElMessage.success('验证码已发送至手机，请注意查收');
      let timeOut = setInterval(() => {
        seconds.value--;
        if (seconds.value <= 0) {
          clearInterval(timeOut);
          seconds.value = 60;
          getCodeFlag.value = false;
        }
      }, 1000);
    } else {
      ElMessage.error(res.msg);
    }
  });
};
// 下一步---验证手机号
const forgetNext = async (formEl: any | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid: any, fields: any) => {
    if (valid) {
      let checkPhone = new FormData();
      checkPhone.append('oldMobile', phoneCheck.value.phone);
      checkPhone.append('validateCode', phoneCheck.value.code);
      RequestLoginAccountValidateOldMobile(checkPhone).then((res: any) => {
        if (res.success == true) {
          steps.value = 2;
          ElMessage.success(res.msg);
        } else {
          ElMessage.error(res.msg);
        }
      });
    } else {
      console.log('error submit!', fields);
    }
  });
};
// 保存密码
const savePassBtn = async (formEl: any | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid: any, fields: any) => {
    if (valid) {
      if (setPassWord.value.oldPassWord !== setPassWord.value.recPassWord) {
        ElMessage.error('两次密码不一致');
      } else {
        let savePass = new FormData();
        savePass.append('validateCode', phoneCheck.value.code);
        savePass.append('mobile', phoneCheck.value.phone);
        savePass.append('newPassword', MD5(setPassWord.value.recPassWord).toString());

        RequestLoginAccountForgetPassword(savePass).then((res: any) => {
          if (res.success == true) {
            ElMessage.success(res.msg);
            steps.value = 3;
          }
        });
      }
    } else {
      console.log('error submit!', fields);
    }
  });
  // let savePass = new FormData()
  // savePass.append('validateCode', phoneCheck.value.code)
  // savePass.append('mobile', phoneCheck.value.phone)
  // savePass.append('newPassword', MD5(setPassWord.value.recPassWord).toString())
  // RequestLoginAccountForgetPassword(savePass).then((res: any) => {
  //     if (res.success == true) {
  //         ElMessage.success(res.msg)
  //         steps.value = 3
  //     }
  // })
};
// 返回登陆
const backLogin = () => {
  phoneCheck.value.phone = '';
  phoneCheck.value.code = '';
  setPassWord.value.oldPassWord = '';
  setPassWord.value.recPassWord = '';
  centerDialogVisible.value = false;
  steps.value = 1;
};
/**
 * 隐私协议
 */
const privacy = () => {
  RequestAgreementGetAgreementUseLocation('（个体商户）劣车宝商城平台隐私政策').then((res: any) => {
    if (res.success == true) {
      res.resultObj.forEach((item: any) => {
        // router.push(`/PDF_preview?file=` + item)
        const routerResolve = router.resolve(`/PDF_preview?file=` + item);
        window.open(routerResolve.href, '_blank');
      });
      //   ElMessage.success("下载成功");
    }
  });
};
/**
 * 服务
 */
const serve = () => {
  RequestAgreementGetAgreementUseLocation('（个体商户）劣车宝商城平台用户服务协议').then((res: any) => {
    if (res.success == true) {
      res.resultObj.forEach((item: any) => {
        const routerResolve = router.resolve(`/PDF_preview?file=` + item);
        window.open(routerResolve.href, '_blank');
      });
    }
  });
};
/* 选项卡 */

// 验证码
let baseImg = ref<any>('');

const getCode = async () => {
  let res = await RequestGetValidateCodeImage();
  baseImg.value = res;
};
const activeName = ref('first');
getCode();
// 刷新验证码
const refreshCode = () => {
  getCode();
};
// setTimeout(() => {
//     getCode()
// }, 10000);

/* 短信登录 */
const phone = ref<any>({
  number: '',
  code: '',
});

/* ##################################### 登录接口 #####################################*/
//记住密码
const onRemmberPassword = () => {
  if (account.value.remmberPsw) {
    console.log('afe', account);
    localStorage.setItem(
      'USER_INFO',
      JSON.stringify({
        username: account.value.username,
        password: MD5(account.value.password).toString(),
        remmberPsw: true,
      }),
    );
  } else {
    localStorage.removeItem('USER_INFO');
  }
};
// 用户账号信息回显
const showUserInfo = () => {
  const userInfo = JSON.parse(localStorage.getItem('USER_INFO')!);
  if (userInfo) {
    console.log(userInfo);
    account.value.username = userInfo.username;
    account.value.password = userInfo.password;
    account.value.remmberPsw = userInfo.remmberPsw;
  }
};
// 登录表单账户数据
const account = ref({
  username: '',
  password: '',
  remmberPsw: false, // 记住密码
  ValidateCode: '', //验证码
  agreement: [], //是否阅读协议
});
showUserInfo();

// 表单验证规则
const rules = ref({
  username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
  password: [{required: true, message: '请输入密码', trigger: 'blur'}],
  ValidateCode: [{required: true, message: '请输入验证码', trigger: 'blur'}],
  agreement: [
    {
      type: 'array',
      required: true,
      message: '请勾选阅读注册协议',
      trigger: 'change',
    },
  ],
});
// 表单对象
const loginRef = ref(null);
const checkAccount = () => {
  const userInfo = JSON.parse(localStorage.getItem('USER_INFO')!);
  if (userInfo.username != account.value.username) {
    localStorage.clear();
  }
};
// 登录表单提交事件
const flag = ref<boolean>(false);
const bindLogin = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async (valid: any, fields: any) => {
    if (valid) {
      flag.value = true;
      if (!localStorage.hasOwnProperty('USER_INFO')) {
        const formAccount = new FormData();
        console.log('密码11111111111', account.value.password);

        formAccount.append('account', account.value.username);
        formAccount.append('password', MD5(account.value.password).toString());
        formAccount.append('validateCode', account.value.ValidateCode);
        RequestLOGIN(formAccount).then((res: any) => {
          if (res.code == 0) {
            ElMessage.success(res.msg);
            localStorage.setItem('TOKEN', res.resultObj.token);
            localStorage.setItem('roleInfo', JSON.stringify(res.resultObj));
            localStorage.setItem('ShopId', JSON.stringify(res.resultObj.shopId));
            // RequestCompaniesNode(res.resultObj.company).then((val: any) => {
            //     console.log('公司信息', val);
            // })
            console.log('2583698', res);

            if (res.resultObj.node == 0) {
              RequestSysFunctionGettree().then((ress: any) => {
                if (ress.code == 0) {
                  flag.value = false;
                  localStorage.setItem('roleRoutes', JSON.stringify(ress.resultObj[0].children));
                  onRemmberPassword(); //记住密码
                  // setTimeout(() => {
                  location.href = '/WelcomePage';
                  localStorage.setItem('isShop', 'true');
                  // }, 200);
                }
              });
            } else {
              RequestEmployeeGetfunctionTree(res.resultObj).then((ress: any) => {
                if (ress.code == 0) {
                  flag.value = false;
                  localStorage.setItem('roleRoutes', JSON.stringify(ress.resultObj[0].children));
                  onRemmberPassword(); //记住密码
                  // setTimeout(() => {
                  location.href = '/WelcomePage';
                  // }, 200);
                  localStorage.setItem('isShop', 'true');
                }
              });
            }
          } else {
            flag.value = false;
            ElMessage.error(res.msg);
          }
        });
      } else {
        const formAccount = new FormData();
        formAccount.append('account', account.value.username);
        formAccount.append('password', MD5(account.value.password).toString());
        formAccount.append('validateCode', account.value.ValidateCode);
        RequestLOGIN(formAccount).then((res: any) => {
          if (res.code == 0) {
            console.log('2583698', res);
            ElMessage.success(res.msg);
            localStorage.setItem('TOKEN', res.resultObj.token);
            localStorage.setItem('roleInfo', JSON.stringify(res.resultObj));
            localStorage.setItem('ShopId', JSON.stringify(res.resultObj.shopId));
            // RequestCompaniesNode(res.resultObj.company).then((val: any) => {
            //     console.log('公司信息', val);
            // })
            if (res.resultObj.node == 0) {
              RequestSysFunctionGettree().then((ress: any) => {
                // console.log(ress);
                if (ress.code == 0) {
                  flag.value = false;
                  localStorage.setItem('roleRoutes', JSON.stringify(ress.resultObj[0].children));
                  // onRemmberPassword()      //记住密码
                  location.href = '/WelcomePage';
                  localStorage.setItem('isShop', 'true');
                }
              });
            } else {
              RequestEmployeeGetfunctionTree(res.resultObj).then((ress: any) => {
                console.log(ress);
                if (ress.code == 0) {
                  flag.value = false;
                  localStorage.setItem('roleRoutes', JSON.stringify(ress.resultObj[0].children));
                  // onRemmberPassword()      //记住密码
                  location.href = '/WelcomePage';
                  localStorage.setItem('isShop', 'true');
                }
              });
            }
          } else {
            flag.value = false;
            ElMessage.error(res.msg);
          }
        });
      }
    }
  });
};
</script>

<style scoped lang="scss">
.blue {
  color: #116cf8;
}

.main {
  width: 100vw;
  height: 100vh;
  background: #f2f7fc;

  .logo {
    width: 10.875rem;
    height: 4rem;
    position: absolute;
    top: 2.5rem;
    left: 2.5rem;
  }

  .left {
    height: 100%;
    width: 40%;
    background: url(../assets/images/login.png) no-repeat;
    background-size: cover;

    .left_img {
      margin-top: 1.25rem;
      margin-left: 1.25rem;
    }
  }

  .right {
    width: 60%;
    height: 100%;

    .right_content {
      width: 26.875rem;

      .right_content_top {
        margin-bottom: 1.25rem;

        h1 {
          font-size: 2rem;
          font-weight: 500;
          color: #222222;
        }

        p {
          font-size: 0.875rem;
          font-weight: 500;
          color: rgba(34, 34, 34, 0.502);

          a {
            color: #116cf8;
          }
        }
      }

      .right_content_from {
        width: 100%;
        background: #ffffff;
        padding: 1.25rem;
        box-shadow: 0.1875rem 0.5rem 3.6875rem 0rem #cee7ff;
        border-radius: 0.5rem 0.5rem 0.5rem 0.5rem;

        .el-input,
        .el-button {
          width: 100%;
          height: 3rem;
        }

        ::v-deep .el-input__wrapper {
          background-color: #f4f4f4;
        }
      }
    }
  }
}

::v-deep .el-tabs__nav-wrap::after {
  height: 0;
}

.code-box {
  position: absolute;
  right: 0;
  top: 0;
  cursor: pointer;
}
</style>
